<template>
  <BaseDialog
    v-model="dialogVisible"
    :title="$t('travelAgency.inquiryForm')"
    width="850px"
    :before-close="handleClose"
  >
    <el-form
      ref="refDialogForm"
      class="set-dialog-form"
      :label-width="language === 'en' ? '180px' : '70px'"
      :model="formData"
      :rules="rules"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label-width="0" class="form-item-table" prop="tripInfo">
            <BaseTable
              ref="refRouteTable"
              :data="props.travelList"
              row-key="id"
              @selection-change="handleSelection2Change"
            >
              <TableColumn type="selection" width="43" reserve-selection />
              <TableColumn :label="$t('fleet.departure')" class="ignore">
                <TableColumn
                  prop="startRegionCode"
                  :label="$t('public.region')"
                  :column-width="routeColumnWidth.startRegionCode"
                >
                  <template #default="{ row }">
                    <span>{{
                      g_utils.getRegionName(row.startRegionCode)
                    }}</span>
                  </template>
                </TableColumn>
                <TableColumn
                  prop="startAddress"
                  :label="$t('public.detailAddress')"
                  :column-width="routeColumnWidth.startAddress"
                />
              </TableColumn>
              <TableColumn :label="$t('fleet.destination')" class="ignore">
                <TableColumn
                  prop="endRegionCode"
                  :label="$t('public.region')"
                  :column-width="routeColumnWidth.endRegionCode"
                >
                  <template #default="{ row }">
                    <span>{{ g_utils.getRegionName(row.endRegionCode) }}</span>
                  </template>
                </TableColumn>
                <TableColumn
                  prop="endAddress"
                  :label="$t('public.detailAddress')"
                  :column-width="routeColumnWidth.endAddress"
                />
              </TableColumn>
              <TableColumn
                prop="startTime"
                :label="$t('fleet.departureTime')"
                :column-width="routeColumnWidth.startTime"
              />
              <TableColumn
                prop="endTime"
                :label="$t('public.endTime')"
                :column-width="routeColumnWidth.endTime"
              />
              <TableColumn
                prop="through"
                :label="$t('fleet.passingScenery')"
                :column-width="routeColumnWidth.through"
              />
              <TableColumn
                prop="mileage"
                label="里程"
                :column-width="routeColumnWidth.mileage"
              />
            </BaseTable>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-row class="dialog-table-filter">
            <TextInput
              v-model="listParams.customerName"
              class="item"
              clearable
              placeholder="客户名称"
            />
            <TextInput
              v-model="listParams.accountId"
              class="item"
              clearable
              placeholder="账号ID"
            />
            <el-button type="primary" @click="handleQuery">{{
              $t('public.search')
            }}</el-button>
            <el-button plain @click="handleReset">{{
              $t('public.reset')
            }}</el-button>
          </el-row>
          <el-form-item
            label-width="0"
            class="form-item-table"
            prop="customerData"
          >
            <div style="width: 100%">
              <BaseTable
                ref="refCustomerTable"
                v-loading="tableLoading"
                :data="customerTableData"
                :row-key="handleRowKey"
                @selection-change="handleSelectionChange"
              >
                <TableColumn type="selection" width="43" reserve-selection />
                <TableColumn
                  prop="nickName"
                  label="供应商名称"
                  :column-width="customerColumnWidth.nickName"
                />
                <TableColumn
                  prop="accountId"
                  label="账号ID"
                  :column-width="customerColumnWidth.accountId"
                />
                <TableColumn
                  prop="userName"
                  label="简介"
                  :column-width="customerColumnWidth.userName"
                />
                <TableColumn
                  prop="action"
                  fixed="right"
                  :label="$t('public.action')"
                  :column-width="customerColumnWidth.action"
                >
                  <template #default="{ row, $index }">
                    <el-button text @click="handleCreateSession(row, $index)"
                      >咨询</el-button
                    >
                  </template>
                </TableColumn>
              </BaseTable>
              <BasePagination
                v-model:page-size="pageSize"
                v-model:current-page="pageNum"
                :total="total"
                @change="getTableList()"
              />
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('travelAgency.price')" prop="customerBudget">
            <TextInput
              v-model="formData.customerBudget"
              verify-type="float"
              :label="$t('travelAgency.price')"
              @blur="handleInputBlur('customerBudget')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('travelAgency.inquiryDesc')" prop="note">
            <TextInput
              v-model="formData.note"
              type="textarea"
              :rows="2"
              :label="$t('travelAgency.inquiryDesc')"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="form-dialog-footer">
        <el-button plain @click="handleClose">{{
          $t('public.cancel')
        }}</el-button>
        <el-button type="primary" @click="handleSubmitForm">{{
          $t('public.confirm')
        }}</el-button>
      </div>
    </template>
  </BaseDialog>
</template>

<script setup>
const props = defineProps({
  id: {
    type: String,
    default: ''
  },
  type: {
    type: String,
    default: ''
  },
  travelList: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update'])
const dialogVisible = defineModel({
  type: Boolean,
  default: false
})
const { language } = storeToRefs(useAppStore())
// const { userInfo } = storeToRefs(useUserStore())

const formLoading = ref(false)
const refDialogForm = ref(null)
const listParams = ref({
  customerName: ''
})
const formData = ref({
  customerData: [],
  tripInfo: [],
  customerBudget: '',
  note: ''
})
const rules = {
  customerData: g_rules.selectRule(g_t('travelAgency.merchantName')),
  tripInfo: g_rules.selectRule(g_t('fleet.trip')),
  customerBudget: g_rules.price({
    required: false
  })
}
const refCustomerTable = ref(null)
const tableLoading = ref(false)
const customerTableData = ref([])
const customerColumnWidth = ref({})
const total = ref(0)
const pageSize = ref(10)
const pageNum = ref(1)
const refRouteTable = ref(null)
const routeColumnWidth = ref({})

watch(
  () => props.travelList,
  nv => {
    nextTick(() => {
      useTableColumnWidth({
        refTable: refRouteTable.value
      }).getTableColumnWidth(data => {
        routeColumnWidth.value = data
      })
    })
  },
  {
    immediate: true
  }
)

onMounted(() => {
  getTableList()
})

const getTableList = () => {
  tableLoading.value = true
  customerTableData.value = []
  g_api.travelAgency
    .apiTeamMerchantList({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      appIdentifier: props.type,
      ...listParams.value
    })
    .then(({ code, data }) => {
      if (code === '200' && data) {
        customerTableData.value = data.items
        total.value = data.total
        useTableColumnWidth({
          refTable: refCustomerTable.value
        }).getTableColumnWidth(data => {
          customerColumnWidth.value = data
        })
      }
    })
    .finally(() => {
      tableLoading.value = false
    })
}

const handleQuery = () => {
  refCustomerTable.value.refBaseTable.clearSelection()
  formData.value.customerData = []
  pageNum.value = 1
  getTableList()
}

const handleReset = () => {
  Object.assign(listParams.value, {
    customerName: ''
  })
  handleQuery()
}

const handleRowKey = row => {
  return row.userName + row.tenantId
}

const handleSelectionChange = val => {
  formData.value.customerData = val
}

const handleCreateSession = row => {
  // tableLoading.value = true
  // g_api.sysMsg
  //   .apiDialogCreate({
  //     fromId: userInfo.value.userId,
  //     toTenantId: row.tenantId,
  //     type: 'group'
  //   })
  //   .then(res => {
  //     if (res.code === '200') {
  //       ElMessage({
  //         message: res.message,
  //         type: 'success'
  //       })
  g_router.push({
    name: 'chatMessage',
    state: {
      params: {
        tenantId: row.tenantId
      }
    }
  })
  //     }
  //   })
  //   .finally(() => {
  //     tableLoading.value = false
  //   })
}

const handleSelection2Change = val => {
  formData.value.tripInfo = val
}

const handleClose = _ => {
  dialogVisible.value = false
}

const handleInputBlur = prop => {
  // 数字化处理
  refDialogForm.value.validateField([prop], vaild => {
    if (vaild && formData.value[prop]) {
      formData.value[prop] = formData.value[prop] * 1
    }
  })
}
const handleSubmitForm = () => {
  if (formLoading.value) return
  refDialogForm.value.validate(valid => {
    console.log('formData.value', formData.value)
    if (!valid) return
    formLoading.value = true
    const { customerData, tripInfo, customerBudget, note } = formData.value
    g_api.travelAgency
      .apiTeamAskOrderCreate({
        tenantIdList: customerData.map(item => item.tenantId),
        type: props.type,
        teamId: props.id,
        carOrderParam: {
          customerBudget,
          peopleCount: tripInfo[0]?.peopleCount || 0,
          note,
          tripInfo
        }
      })
      .then(res => {
        if (res.code === '200') {
          ElMessage({
            message: res.message,
            type: 'success'
          })
          handleClose()
          emit('update')
        }
      })
      .finally(() => {
        formLoading.value = false
      })
  })
}
</script>

<style scoped lang="scss">
.form-item-table {
  :deep(.el-scrollbar__wrap) {
    max-height: 200px;
    overflow-y: auto;
  }
  // 修改错误提示导致的选择框样式变红
  &.is-error {
    :deep(.el-input__wrapper),
    :deep(.el-select__wrapper) {
      box-shadow: 0 0 0 1px var(--select-border-color) inset !important;
    }
  }
}
</style>
